package com.shenglaotuan.community.common.config;

import com.shenglaotuan.community.common.entity.ResponseResult;
import com.shenglaotuan.community.common.exception.*;
import com.shenglaotuan.community.user.exception.*;
import io.jsonwebtoken.SignatureException;
import org.springframework.validation.BeanPropertyBindingResult;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ValidationException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(value = { ServiceException.class, ValidationException.class, SignatureException.class, BindException.class})
    public ResponseResult<Void> serviceExceptionHandler(Exception e){
        ResponseResult<Void> result = new ResponseResult<>();
        result.setMessage(e.getMessage());

        if(e instanceof SignatureException){
            result.setCode(4001);
        }else if(e instanceof ValidationException){
            result.setCode(4002);
        }else if(e instanceof EmailDuplicateException){
            result.setCode(4003);
        }else if(e instanceof CodeExistException){
            result.setCode(4004);
        }else if(e instanceof InvateCodeNotMatchException){
            result.setCode(4005);
        }else if(e instanceof PasswordNotMatchException){
            result.setCode(4006);
        }else if(e instanceof UsernameDuplicateException){
            result.setCode(4007);
        }else if(e instanceof UserNotExistException){
            result.setCode(4008);
        }else if(e instanceof ValidCodeNotMatchException){
            result.setCode(4009);
        }else if(e instanceof UploadEmptyException){
            result.setCode(4010);
        }else if(e instanceof UploadSizeException){
            result.setCode(4011);
        }else if(e instanceof UploadTypeException){
            result.setCode(4012);
        }else if(e instanceof NicknameDuplicateException){
            result.setCode(4013);
        }else if(e instanceof BindException){
            result.setCode(4014);
            BindException ex = (BindException)e;
            result.setMessage(ex.getBindingResult().getFieldError().getDefaultMessage());
        }else if(e instanceof InsertException){
            result.setCode(5001);
        }else if(e instanceof UploadIOException){
            result.setCode(5005);
        }else{
            result.setCode(0);
        }
        return result;
    }

    @ExceptionHandler(value = {Exception.class})
    public ResponseResult<Void> exceptionHandler(Exception e){
        ResponseResult<Void> result = new ResponseResult<>();
        e.printStackTrace();
        result.setMessage("系统故障，请稍后再试");
        result.setCode(1);
        return result;
    }
}
